package com.study.config;
import com.study.common.AppUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.study.common.Constant.USER_KEY;

/**
 * 登录拦截器
 * 
 */
@Configuration
public class LoginInterceptor extends HandlerInterceptorAdapter implements WebMvcConfigurer {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("preHandle。。。。。");
		//判断请求中是否存在对应的session对象
		if (request.getSession().getAttribute(USER_KEY) == null) {
			response.sendRedirect("/login");
			//session中无对应对象元素，且请求方式为ajax
			if (AppUtils.isAjax(request)) {
				response.sendError(401);
			} else {
				//跳转到页面首页
				response.sendRedirect(request.getContextPath() + "/index");
			}
			return false;//拦截
		}								   
		return true;//放行
	}

	/**
	 *  登录拦截的地址
	 * 假设请求http://localhost:8080/emp/list/1002。如果没有对应的session对象，则会默认转到首页
	 * webapp/index.jsp
	 * 首页不存在，则会启动全局异常，跳转到error.jsp页面
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		System.out.println("登录地址拦截。。。。。");
        registry.addInterceptor(this)
        //拦截的地址
        .addPathPatterns("/afterSale/**",
				"/beforeSale/**","/customer/**","/depot/**","/getCustomer/**","/goods/**","/onSale/**","/permission/**")
		//拦截排除的地址
        .excludePathPatterns("/", "/login", "/error","/js/**","/css/**","/imgs/**");
	}
}
